package net.qhzw.vip.qiyu.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.alibaba.fastjson.JSON;
import com.github.binarywang.wxpay.bean.order.WxPayNativeOrderResult;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import lombok.Setter;
import net.qhzw.vip.qiyu.component.ServerConfig;
import net.qhzw.vip.qiyu.config.WxPayConfiguration;
import net.qhzw.vip.qiyu.result.JsonResult;
import net.qhzw.vip.qiyu.service.DtsCarFeedbackService;
import net.qhzw.vip.qiyu.service.TestService;
import net.qhzw.vip.qiyu.task.ScheduledTask;
import net.qhzw.vip.qiyu.util.IPHelper;
import org.apache.axis.utils.ByteArrayOutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("test")
public class TestController {

    @Setter
    private String[] ignoreUrls;


    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DtsCarFeedbackService dtsCarFeedbackService;

    @Autowired
    private TestService testService;


    @Autowired
    private ScheduledTask scheduledTask;

    @GetMapping("/execution")
    public JsonResult execution() {
        scheduledTask.execution();
        return JsonResult.ok();
    }


    @ResponseBody
    @GetMapping("pay")
    public JsonResult pay(WxPayUnifiedOrderRequest request) {
        WxPayConfig wxPayConfig = new WxPayConfig();
        wxPayConfig.setSubMchId(request.getSubMchId());
        WxPayService wxPayService = WxPayConfiguration.getPayService(wxPayConfig);
        WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
        String outTradeNo = UUID.randomUUID().toString().replaceAll("-", "");
        String productId = UUID.randomUUID().toString().replaceAll("-", "");
        orderRequest.setOutTradeNo(outTradeNo);
        orderRequest.setBody("测试");
        orderRequest.setTotalFee(5);
        orderRequest.setNotifyUrl("http://etsa5x.natappfree.cc");
        orderRequest.setTradeType(WxPayConstants.TradeType.NATIVE);
        orderRequest.setSpbillCreateIp(IPHelper.getIpAddr());
        orderRequest.setProductId(productId);
        //orderRequest.setSubMchId("1630679820");
        String code = "";
        WxPayNativeOrderResult orderResult = null;
        try {
            orderResult = wxPayService.createOrder(orderRequest);
            String codeUrl = orderResult.getCodeUrl();
            code = qrCode(codeUrl);
        } catch (WxPayException e) {
            e.printStackTrace();
            //throw new RuntimeException("二维码生成失败!稍后重试!");
            return JsonResult.fail(JSON.toJSONString(e));
        }
        return JsonResult.ok(code);
    }


    /**
     * 生成支付二维码
     *
     * @param codeUrl
     * @return
     */
    public String qrCode(String codeUrl) {
        String result = "data:image/jpeg;base64,";
        BufferedImage bufferedImage = QrCodeUtil.generate(codeUrl,
                175,
                175);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        try {
            ImageIO.write(bufferedImage, "png", stream);
            String encode = Base64.encode(stream.toByteArray());
            return result + encode;
        } catch (IOException e) {
            throw new RuntimeException("二维码生成失败!稍后重试!");
        }
    }


    @GetMapping("hello")
    public String testTran() {
        return "hello";
    }


    @GetMapping
    public JsonResult jsonReader() {
        //dtsCarFeedbackService.execute();

        return JsonResult.ok(ignoreUrls);
    }


    @GetMapping("send")
    public String send(HttpServletRequest request) {

        String htmlContent = "";
        String authorization = request.getHeader("Authorization");
        //创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", authorization);
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        String url = serverConfig.getUrl();
        url += "/test/ok";
        Map<String, String> param = new HashMap<>();
        param.put("username", "zhangsan");
        param.put("password", "123456");
        String paramJosn = JSON.toJSONString(param);
        HttpEntity entity = new HttpEntity<>(paramJosn, headers);
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        htmlContent = responseEntity.getBody();
        return htmlContent;
    }





}

